/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package tools;

import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * A class that handles sending emails for the email-to-sms functionality
 * 
 * 
 */
public class MailClient {
   private final String host;
   private final String username;
   private final String password;
   private final int port;

   public MailClient(final String host, final String username, final String password, final int port) {
	  this.host = host;
	  this.username = username;
	  this.password = password;
	  this.port = port;
   }

   /**
    * Sends an email
    * 
    * @param from
    * @param to
    * @param subject
    * @param content
    * @throws MessagingException
    * @throws AddressException
    */
   public void sendMail(final String from, final List<String> to, final String subject, final String content)
		 throws MessagingException, AddressException {
	  final Properties props = System.getProperties();
	  props.put("mail.smtp.host", host);
	  props.put("mail.smtp.port", String.valueOf(port));
	  props.put("mail.smtp.starttls.enable", "true");

	  final Session session = Session.getDefaultInstance(props, null);

	  final Message message = new MimeMessage(session);
	  message.setFrom(new InternetAddress(username));
	  for (final String recepient : to) {
		 message.addRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
	  }
	  message.setSubject(from + " says: " + subject);
	  message.setContent(content, "text/plain");

	  props.put("mail.smtp.auth", "true");

	  final Transport t = session.getTransport("smtp");
	  try {
		 t.connect(username, password);
		 t.sendMessage(message, message.getAllRecipients());
	  } finally {
		 t.close();
	  }
   }
}